//
//  LBFramebuffer.mm
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 11/16/12.
//  Copyright (c) 2012 UIT. All rights reserved.
//

#ifndef OpenGLGame_LBFramebuffer_mm
#define OpenGLGame_LBFramebuffer_mm

#include "LBFramebuffer.h"
#include "LBTexture.h"
#include "LBGraphics.h"
LBFramebuffer::LBFramebuffer(LBTexture* textureToRenderTo){
    texture = textureToRenderTo;
    glGenFramebuffers(1, &frameBuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
    
    
    glBindTexture(GL_TEXTURE_2D, texture->getTexId());
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->getTexId(), 0);
    
    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if(status != GL_FRAMEBUFFER_COMPLETE){
        printf("Fail create framebuffer: %x\n", status);
    }
    
    glBindTexture(GL_TEXTURE_2D, 0);	
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

void LBFramebuffer::beginRenderToTexture(){
    LBGraphics* g = LBGraphics::getInstance();
    g->setWindowsSize(texture->getWidth(), texture->getHeight());
    g->viewport(0, 0, texture->getWidth(), texture->getHeight());
    glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
}

LBFramebuffer::~LBFramebuffer(){
    glDeleteFramebuffers(1, &frameBuffer);
}

void LBFramebuffer::imageData(GLubyte** imgData){
    glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
    
    int x = 0, y = 0;
    int width = texture->getWidth();
    int height = texture->getHeight();
    int dataLength = width*height*4;
    
    GLubyte *data = (GLubyte *)malloc(dataLength * sizeof(GLubyte));
    
    glPixelStorei(GL_PACK_ALIGNMENT, 4 );
    glReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data);
    
    *imgData = data;
}

#endif
